package com.seaboxdata.interfaceJob;

import com.alibaba.fastjson.JSONObject;
import com.seaboxdata.entity.Disposial;
import com.seaboxdata.entity.DisposialVo;
import com.seaboxdata.service.DpjfxtDisposialService;
import com.seaboxdata.service.DpjfxtTokenService;
import com.seaboxdata.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @create 2021-04-27 16:20
 **/
@Component
@Configuration
@Slf4j
public class DpjfxtDisposialJob {

    @Autowired
    private DpjfxtTokenService dpjfxtTokenService;

    @Autowired
    private DpjfxtDisposialService dpjfxtDisposialService;

    @Value("${dpjfxt.diposal.url}")
    private String url;

    @Value("${interface.isTest}")
    private String isTest;

    @Scheduled(cron = "${dpjfxt.diposal.interval}")//每隔5分钟执行一次
    public void doCollect() {
        log.info("get diposal begin");
        //如果是测试,直接退出
        if ("true".equals(isTest)) {
            return;
        }
        String token = dpjfxtTokenService.getToken();
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("content-type", "application/json");
        if (StringUtils.isEmpty(token)) {
            log.error("get token error");
            return;
        }
        headerMap.put("token", token);
        HttpUtils.Response response = HttpUtils.doPost(url, new JSONObject().toJSONString(), "utf-8", headerMap);
        if (response.getStatusCode() == 200) {
            String result = response.getResponseData();
            DisposialVo disposialVo = JSONObject.parseObject(result, DisposialVo.class);
            if (disposialVo.getStatus() != 200) {
                log.error(disposialVo.getMessage());
            } else {
                //将当天获取的值存入数据库
                List<Disposial> disposials = disposialVo.getData();
                if (!CollectionUtils.isEmpty(disposials)) {
                    disposials.forEach(x -> x.setCjsj(new Date()));
                    dpjfxtDisposialService.saveBatch(disposials);
                }
            }
        }
    }
}
